<template>
	<view class=" trading">
		<view class="ceiling" :style="{ 'padding-top': statusBarHeight + 'px' }"></view>
		<!--  表头 -->
		<searchHead goback='gobackF' background="#EE515A" title='交易' searchTip='searchimg'></searchHead>
		<view class='dynamicBox bgff'>
			<view class="dynamicTab center">
				<view @click="tonavigateTo('/pages/trading/buy')" :class="tabIndex == 0?'active':''" class="tabItem flex-f1 tx-c">买入</view>
				<view @click="tonavigateTo('/pages/trading/sell')" :class="tabIndex == 1?'active':''" class="tabItem flex-f1  tx-c">卖出</view>
			</view>
		</view>
		<view style="height: 20rpx;background-color: #F2F2F2;width: 100vw;"></view>
		<!-- 数量 -->
		<view class="tradingContainer">
			<view class="plr15">
				<view class="search start">
					<image src="/static/imgs/mi_slices/mi_slices.png" mode=""></image>
					<input class="flex-f1" v-model="value" type="text" @input="onInput" placeholder="请输入股票或代码查询" border-color="red" :border="true" />
				</view>
			</view>
			<!-- 原来的股票名称 -->
			<view class="plr15" style="margin-top: 8upx;display: none;">
				<input v-model="shares.N" type="text" style="color: #F4F5F6;" placeholder="股票名称" :disabled="true" border-color="red" :border="true" />
			</view>
		</view>
		<view class="padding-lr bg_12161F">
			<!-- 重写的股票名称 -->
			<view class="flex justify-between align-center padding-tb border-bottom-1B202C">
				<view class="text-black text-df">股票名称</view>
				<view class="flex justify-end align-center text-xl text-black" style="text-align: right;">
					<text style="">{{shares.N}}</text>
				</view>
			</view>
			<view class="flex justify-between align-center padding-tb border-bottom-1B202C">
				<view class="text-black text-df">最新价格</view>
				<view class="flex justify-end align-center text-df color_EE4343">
					<view class="margin-right-sm" v-if="flag == 1">{{shares.P}}</view>
					<view class="margin-right-sm" v-if="flag == 1">
						<text style="color: red;" v-if="shares.P>=shares.YC">{{(shares.P-shares.YC).toFixed(2)}}</text>
						<text style="color: #3ca509;" v-if="shares.P<shares.YC">{{(shares.P-shares.YC).toFixed(2)}}</text>
					</view>
					<view class="" v-if="flag == 1">
						<text style="color: red;" v-if="shares.P>=shares.YC">{{((shares.P-shares.YC) *10/shares.YC *10).toFixed(2)}}%</text>
						<text style="color: #3ca509;" v-if="shares.P<shares.YC">{{((shares.P-shares.YC) *10/shares.YC *10).toFixed(2)}}%</text>
					</view>
				</view>
			</view>
			<view class="flex justify-between align-center padding-tb border-bottom-1B202C">
				<view class="text-black text-df">买入股数</view>
				<view class="flex justify-end align-center text-xl text-black">
					<yp-number-box style="color: #000000;" :value="buyNum" @change="change()" :min="100" :max="100000000" :step="100"></yp-number-box>
				</view>
			</view>
			<view class="flex justify-between align-center padding-tb border-bottom-1B202C">
				<view class="text-black text-df">建仓金额</view>
				<view class="start">
					<view @click="fourPoint()" class="btn1 mr8 text-black" :class="btnIndex == 0?'active':''">1/4</view>
					<view @click="twoPoint()" class="btn1 mr8 text-black" :class="btnIndex == 1?'active':''">1/2</view>
					<view @click="all()" class="btn1 text-black" :class="btnIndex == 2?'active':''">全仓
					</view>
				</view>
			</view>
			<view class="flex justify-between align-center padding-tb border-bottom-1B202C">
				<view class="text-black text-df">可买</view>
				<view class="flex justify-end align-center text-df color_99A2B5">{{flag == 1?parseInt(user.money/shares.P):''}}股</view>
			</view>
			<view class="flex justify-between align-center padding-tb">
				<view class="text-black text-df">可用额度</view>
				<view class="flex justify-end align-center text-df color_99A2B5">{{user.keYongMoney}}元</view>
			</view>
		</view>
		<view class="padding-lr-xl padding-top-lg flex flex-direction">
			<button class="cu-btn bg-blue lg"  @click.stop="buy()">席位买入</button>
		</view>
	
		
		<!-- 新版本 end -->

		<view>
			<u-toast ref="uToast" />
		</view>


		<!-- 弹出窗部分 -->
		<template>
			<u-popup v-model="popup.buy_show" mode="center" border-radius="14" width="70%" height="auto">
				<view class="pop-box">
					<view class="pop-center pop-title">{{popup.title}}</view>
					<scroll-view scroll-y class="pop-info-box pop-text">
						<u-row class="pop-text pop-info">
							<u-col span="12" class="pop-margin">
								<text class="pop-left">买入账户：</text>
								<text class="pop-right">{{ user.phone }}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">股票名称：</text>
								<text class="pop-right">{{shares.N}}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">股票代码：</text>
								<text class="pop-right">{{shares.FS}}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">委托价格：</text>
								<text class="pop-right">{{shares.P}}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">委托数量：</text>
								<text class="pop-right">{{buyNum}}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">委托金额：</text>
								<text class="pop-right">{{shares.P*buyNum}}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">预估交易费用：</text>
								<text class="pop-right">{{shares.P*buyNum*insurance.fee}}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">股票投保：</text>
								<text class="pop-right">{{shares.P*buyNum*insurance.insurance}}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">总金额：</text>
								<text class="pop-right">{{ (shares.P*buyNum + shares.P*buyNum*insurance.fee + shares.P*buyNum*insurance.insurance).toFixed(3)  }}</text>
							</u-col>
						</u-row>
					</scroll-view>
					<view class="pop-margin">
						<u-row>
							<u-col span="6">
								<u-button @click="popup.buy_show = false" type="info" style=" width: 100%;" size="medium">取消</u-button>
							</u-col>
							<u-col span="6">
								<u-button @click="is_insurance_agree()" type="error" style=" width: 100%;" size="medium">确认买入</u-button>
							</u-col>
						</u-row>
					</view>

				</view>
			</u-popup>

			<u-popup v-model="popup.sell_show" mode="center" border-radius="14" width="70%" height="auto">
				<view class="pop-box" v-if="myOrder[0]">
					<view class="pop-center pop-title">{{popup.sell_title}}</view>
					<scroll-view scroll-y class="pop-info-box pop-text">
						<u-row class="pop-text pop-info">
							<u-col span="12" class="pop-margin">
								<text class="pop-left">买入账户：</text>
								<text class="pop-right">{{ user.phone }}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">股票名称：</text>
								<text class="pop-right">{{ myOrder[0].sname }}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">股票代码：</text>
								<text class="pop-right">{{ myOrder[0].scode }}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">委托价格：</text>
								<text class="pop-right">{{ myOrder[0].smoney }}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">委托数量：</text>
								<text class="pop-right">{{ myOrder[0].snum }}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">委托金额：</text>
								<text class="pop-right">{{ myOrder[0].totalmoney }}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">预估交易费用：</text>
								<text class="pop-right">{{ myOrder[0].fee }}</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">保险理赔：</text>
								<text class="pop-right" v-if="shares.P < myOrder[0].smoney">有效</text>
								<text class="pop-right" v-if="shares.P > myOrder[0].smoney">无效</text>
							</u-col>
							<u-col span="12" class="pop-margin">
								<text class="pop-left">保险金额：</text>
								<text class="pop-right">{{ myOrder[0].insurance_money }}</text>
							</u-col>
						</u-row>
					</scroll-view>
					<view class="pop-margin">
						<u-row>
							<u-col span="6">
								<u-button @click="popup.sell_show = false" type="info" style=" width: 100%;" size="medium">取消</u-button>
							</u-col>
							<u-col span="6">
								<u-button @click="sell('insurance_url')" type="error" style=" width: 100%;" size="medium">确认卖出</u-button>
							</u-col>
						</u-row>
					</view>

				</view>
			</u-popup>
		</template>
		
	</view>
</template>

<script>
	import searchHead from "@/component/searchHead/searchHead.vue"
	export default {
		components: {
			searchHead,
		},
		data() {
			return {
				statusBarHeight: getApp().globalData.statusBarHeight, //状态栏高度
				clickTime:0, // 上次点击时间 
				tabIndex: 0,
				btnIndex: '',
				// 新增 
				popup: {
					buy_show: false,
					title: '投保委托买入确认',
					sell_show: false,
					sell_title: '投保委托卖出确认',
				},
				insurance: {
					fee: 0,
					insurance: 0,
					shares: 0
				},
				// 基本信息
				user: [],
				// 持仓
				order: [],
				indexButton: '-1', //初始状态不显示
				// 买入
				value: '',
				shares: {},
				buyNum: 100,
				flag: 0,
				myOrder: [],
			};
		},
		methods: {
			// 跳转页面
			tonavigateTo(url) {
				uni.navigateTo({
					url: url
				})
			},
			// 新增内容
			getSharesQuery: function() {
				this.$Request.post(this.$api.index.getSharesQuery, {
					code: this.code,
				}).then(res => {
					this.shares = res.data;
				})
			},
			getUser: function() {
				this.$Request.post(this.$api.index.getUser).then(res => {
					this.user = res.data;
				})
			},
			// 获取用户持仓
			getOrders() {
				this.$Request.post(this.$api.index.getOrders).then(res => {
					this.order = res.data;
					this.data = res;
				})
			},
			// 获取用户订单
			getOrder() {
				this.$Request.post(this.$api.index.getOrder, {
					code: this.code,
				}).then(res => {
					this.myOrder = res.data;
				})
			},
			// 买入 股票操作
			// 监听输入框 查询股票 及持有订单
			onInput(e) {
				if (!e) {
					this.shares = {};
					this.flag = 0;
					return;
				}
				this.$Request.post(this.$api.index.searchShares, {
					// 从对象转向字符串
					where: e.detail.value,
				}).then(res => {
					if (res.data.length > 0) {
						this.shares = res.data[0];
						this.flag = 1;
						this.$Request.post(this.$api.index.getOrder, {
							code: this.shares.FS,
						}).then(res => {
							this.myOrder = res.data;
						})
					} else {
						this.$refs.uToast.show({
							title: '无此股票',
						})
						this.shares = {};
						this.flag = 0;
						this.myOrder = {};
					}
				})
			},
			// 买入 全仓
			all() {
				this.btnIndex = 2
				this.buyNum = parseInt(this.user.money / this.shares.P);
				// 增加求余
				let numBuy = parseInt(this.buyNum / 100)
				this.buyNum = numBuy * 100

				if (this.buyNum < 100) {
					this.$refs.uToast.show({
						title: '最少买入100股',
					})
					return;
				}
			},
			twoPoint() {
				this.btnIndex = 1
				this.buyNum = parseInt(this.user.money / this.shares.P / 2)
				// 增加求余
				let numBuy = parseInt(this.buyNum / 100)
				this.buyNum = numBuy * 100

				if (this.buyNum < 100) {
					this.$refs.uToast.show({
						title: '最少买入100股',
					})
					return;
				}
			},
			threePoint() {
				this.buyNum = parseInt(this.user.money / this.shares.P / 3)
				// 增加求余
				let numBuy = parseInt(this.buyNum / 100)
				this.buyNum = numBuy * 100

				if (this.buyNum < 100) {
					this.$refs.uToast.show({
						title: '最少买入100股',
					})
					return;
				}
			},
			fourPoint() {
				this.btnIndex = 0
				this.buyNum = parseInt(this.user.money / this.shares.P / 4)
				// 增加求余
				let numBuy = parseInt(this.buyNum / 100)
				this.buyNum = numBuy * 100

				if (this.buyNum < 100) {
					this.$refs.uToast.show({
						title: '最少买入100股',
					})
					return;
				}
			},
			// 买入主函数
			buy(type) {
				this.$Request.post(this.$api.index.getUser).then(res => {
					if (res.data.ischeck == 0) {
						this.$refs.uToast.show({
							title: '请先实名认证',
						})
						setTimeout(() => {
							uni.navigateTo({
								url: "/pages/member/realname", //未实名认证去实名认证
							});

						}, 2000);

					} else {
						// 防止重复点击
						let timestamp = Date.parse(new Date());
						timestamp = timestamp / 1000 //得到秒
						console.log(timestamp)
						console.log(this.clickTime)
                        //return
						if(timestamp - this.clickTime > 30){
							// 执行购买动作
							this.buyShares(type);
						}else{
							this.$refs.uToast.show({
								title: '1分钟内操作过于频繁，请稍后再试',
							})
						}
						this.clickTime = timestamp
					}
				})
			},
			buyShares(type) {
				if (this.buyNum < 100) {
					this.$refs.uToast.show({
						title: '最少买入100股',
					})
					return;
				}
				if (this.buyNum * this.shares.P > this.user.money + this.user.djmoney) {
					this.$refs.uToast.show({
						title: '余额不足！',
					})
					return;
				}
				if (this.flag == 0) {
					this.$refs.uToast.show({
						title: '请选择一支股票',
					})
					return;
				}
				// 保险购买，提示窗口
				// if(type == 'insurance'){
				// 	this.popup.buy_show = true;
				// 	return 
				// }
				this.code = this.shares.FS;
				//涨停的需要查看是否设置可买金额
				let upStop = (this.shares.YC + this.shares.YC * 0.1).toFixed(2); //涨停价格
				// 特殊 SZ300开头的股票 ，跟 SH688 开头的股票，他们是20% 的涨停，坑货，所有要重新判定
				console.log(this.shares.FS)
				console.log("位置：")
				console.log(this.shares.FS.indexOf('SZ300'))
				console.log(this.shares.FS.indexOf('SH688'))
				if(this.shares.FS.indexOf('SZ300') == 0 || this.shares.FS.indexOf('SH688') == 0){
					console.log("特殊股票 20% 涨停")
					upStop = (this.shares.YC + this.shares.YC * 0.2).toFixed(2);
				}
				if (this.shares.P >= upStop) { // 涨停买入
					let that = this;
					this.$Request.post(this.$api.index.checkSharesStop, {
						code: this.code,
					}).then(res => {
						// 没有数据
						if (!res.data) {
							this.$refs.uToast.show({
								title: "委托失败，该股已涨停!",
							})
							return
						}
						// 没有空间了
						if (res.data.agreeMoney == 0) {
							this.$refs.uToast.show({
								title: "委托失败，该股已经涨停!",
							})
							return
						}
						// 正常返回数据
						if (res.code == 1) {
							this.$refs.uToast.show({
								title: res.msg,
							})
							return
						}
						// 购买金额大于 设置百分比 * 成交额 则不允许购买
						if (this.buyNum * this.shares.P > (this.shares.A * res.data.agreeMoney / 100)) {
							this.$refs.uToast.show({
								title: "超出市场成交量!",
							})
							return
						}
						// 提示购买中
						uni.showLoading({
							title: '正在抢购',
							mask: true
						})
						// 执行 抢买的 接口
						setTimeout(() => {
							let request_url = that.$api.index.buy;

							console.log("涨停 买入购买接口:" + request_url)

							// 保险的购买接口不一样
							// if(type == 'insurance_url'){
							// 	//保险购买接口
							// 	request_url = that.$api.index.buyInsurance;
							// }

							that.$Request.post(request_url, {
								scode: that.shares.FS,
								sname: that.shares.N,
								smoney: that.shares.P,
								snum: that.buyNum,
							}).then(res => {
								uni.hideLoading();
								that.$refs.uToast.show({
									title: res.msg,
								})
								if (res.code == "0") {
									that.getOrder();
									that.getUser();
									that.getOrders();
								}
							})
						}, 5000);
					})

				} else { // 普通买入
					let that = this;
					uni.showLoading({
						title: '正在抢筹买入中......',
						mask: true
					})
					// 执行 抢买的 接口
					setTimeout(() => {
						let request_url = that.$api.index.buy;

						console.log("普通买入购买接口:" + request_url)

						// if(type == 'insurance_url'){
						// 	//保险购买接口
						// 	request_url = that.$api.index.buyInsurance;
						// }

						that.$Request.post(request_url, {
							scode: that.shares.FS,
							sname: that.shares.N,
							smoney: that.shares.P,
							snum: that.buyNum,
						}).then(res => {
							uni.hideLoading();
							that.$refs.uToast.show({
								title: res.msg,
							})
							if (res.code == "0") {
								that.getOrder();
								that.getUser();
								that.getOrders();
							}
						})
					}, 5000);
				}
			},
			checkLogin() {
				this.$Request.get(this.$api.index.checkLogin).then(res => {
					if (res.code == 1) {
						uni.navigateTo({
							url: "/pages/public/login/login",
						})
					} else if (res.code == 0) {
						this.$Request.get(this.$api.index.userInfo).then(res => {
							if (res.data.ischeck == 1) {
								uni.showModal({
									content: "实名认证，机构正在审核中",
									confirmText: "确定",
									cancelText: "取消"
								})
							} else if (res.data.ischeck == 0) {
								var ischeck = res.data.ischeck;
								uni.showModal({
									content: "未实名认证",
									confirmText: "去认证",
									cancelText: "取消",
									success: (res) => {
										if (res.confirm) {
											uni.navigateTo({
												url: "/pages/member/realname?flag=" + ischeck,
											})
										} else if (res.cancel) {

										}
									}
								})
							} else if (res.data.ischeck == 3) {
								var ischeck = res.data.ischeck;
								uni.showModal({
									content: "实名认证未通过审核，请重新提交",
									confirmText: "确定",
									cancelText: "取消",
									success: (res) => {
										if (res.confirm) {
											uni.navigateTo({
												url: "/pages/member/realname?flag=" + ischeck,
											})
										} else if (res.cancel) {

										}
									}
								})
							}
						})
					}
				})
			},
			// methods 函数结束
		},
		onShow() {
			this.checkLogin()
			this.getOrders()
			this.getUser()
			let _self = this;
			let that = this;
			uni.$on('change', function(data) {
				that.buyNum = parseInt(data / 100) * 100;
			})
			this.timer = setInterval(function() {
				_self.getOrders();
				_self.getUser();
			}, 10000);
		},
		onHide() {
			clearInterval(this.timer)
		},
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		onLoad(e) {
			this.name = e.name;
			this.code = e.code;
			if (e.name || e.code) {
				this.value = e.name + e.code;
				this.flag = 1
			}

			this.getSharesQuery();
			this.getUser();
			this.getOrder();
			let that = this;
			uni.$on('change', function(data) {
				that.buyNum = parseInt(data / 100) * 100;
			})
		}
	}
</script>

<style lang="scss" scoped>
	@import "./buyAndSell.scss";
</style>
